package cn.springsoter.core.tool.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Map;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

import com.google.common.collect.Maps;

/**
 * <p>
 * 由于非对称加密速度极其缓慢，一般文件不使用它来加密而是使用对称加密，<br/>
 * 非对称加密算法可以用来对对称加密的密钥加密，这样保证密钥的安全也就保证了数据的安全
 * </p>
 * 
 * <p>
 * 公私钥对可以在线生成：http://www.metools.info/code/c80.html <br/>
 * 注意：此工具类只支持密钥长度小于等于1024bit以下的
 * </p>
 * 
 */
public class RSAUtil {
	/**
	 * 加密算法RSA
	 */
	private static final String KEY_ALGORITHM = "RSA";
 
	private static final int MAX_ENCRYPT_BLOCK = 117;
 
	private static final int MAX_DECRYPT_BLOCK = 128;
	
	/**
	 * 私钥缓存key
	 */
	public static final String RSA_PRIVATE_CACHE_KEY = "RSAPrivateKey";
	/**
	 * 公钥缓存key
	 */
	public static final String RSA_PUBLIC_CACHE_KEY = "RSAPublicKey";
	
	/**
	 * 生成RSA公、私钥对
	 * 
	 * @return
	 */
	public static Map<String, String> generateRSAKeyPair() {
		Map<String, String> keyPairMap = Maps.newHashMap();
		try {
			KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
			generator.initialize(1024);
			KeyPair keyPair = generator.generateKeyPair();
			RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
			RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();
			keyPairMap.put(RSA_PUBLIC_CACHE_KEY, Base64.encodeBase64String(publicKey.getEncoded()));
			keyPairMap.put(RSA_PRIVATE_CACHE_KEY, Base64.encodeBase64String(privateKey.getEncoded()));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
		return keyPairMap;
	}
	
	/**
	 * method will close inputSteam
	 * 
	 * @param pemFileInputStream
	 * @return
	 */
	public static PublicKey loadPublicKey(InputStream pemFileInputStream) {
		return readPublicKey(FileUtil.readPEMFile(pemFileInputStream));
	}
 
	/**
	 * method will close inputSteam
	 * 
	 * @param pkcs8PemFileInputStream
	 * @return
	 */
	public static PrivateKey loadPrivateKey(InputStream pkcs8PemFileInputStream) {
		return readPrivateKey(FileUtil.readPEMFile(pkcs8PemFileInputStream));
	}
 
	/**
	 * 
	 * @param pemFile
	 * @return
	 */
	public static PublicKey loadPublicKey(String pemFile) {
		return readPublicKey(FileUtil.readPEMFile(pemFile));
	}
 
	/**
	 * 
	 * @param pkcs8PemFile
	 * @return
	 */
	public static PrivateKey loadPrivateKey(String pkcs8PemFile) {
		return readPrivateKey(FileUtil.readPEMFile(pkcs8PemFile));
	}
 
	/**
	 * 
	 * @param pkcs8Base64String
	 *            <p>
	 *            delete the first and last line, sth. like below: -----BEGIN
	 *            PRIVATE KEY----- -----END PRIVATE KEY-----
	 *            </p>
	 * @return
	 */
	public static PrivateKey readPrivateKey(String pkcs8Base64String) {
		if(!Base64.isBase64(pkcs8Base64String)) {
			//如果不是base64字符串，则报错
			throw new RuntimeException("InvalidKeySpecException");
		}
		byte[] keyByte = Base64.decodeBase64(pkcs8Base64String);
		try {
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyByte);
			RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec);
 
			return privateKey;
		} catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
			throw new RuntimeException(ex);
		}
	}
 
	public static PublicKey readPublicKey(String pkcs8Base64String) {
		if(!Base64.isBase64(pkcs8Base64String)) {
			//如果不是base64字符串，则报错
			throw new RuntimeException("InvalidKeySpecException");
		}
		byte[] keyByte = Base64.decodeBase64(pkcs8Base64String);
		try {
			X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyByte);
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			PublicKey publicKey = (PublicKey) keyFactory.generatePublic(x509KeySpec);
 
			return publicKey;
		} catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
			throw new RuntimeException(ex);
		}
	}
 
	/**
	 * <P>
	 * 私钥解密
	 * </p>
	 * 
	 * @param encryptedData
	 *            已加密数据
	 * @param privateKey
	 * @return
	 */
	public static byte[] decryptByPrivateKey(byte[] encryptedData, PrivateKey privateKey) {
		try {
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
 
			return cipher.doFinal(encryptedData);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}
 
	/**
	 * 公钥加密
	 * 
	 * @param content
	 *            待加密内容
	 * @param publicKey
	 *            公钥
	 * @param charset
	 *            content的字符集，如UTF-8, GBK, GB2312
	 * @return 密文内容 base64 ASCII
	 */
	public static String encryptByPublicKey(String content, PublicKey publicKey, String charset) {
		try {
			Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			byte[] data = (charset == null || charset.isEmpty()) ? content.getBytes() : content.getBytes(charset);
			int inputLen = data.length;
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int offSet = 0;
			byte[] cache;
			int i = 0;
			// 对数据分段加密
			while (inputLen - offSet > 0) {
				if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
					cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
				} else {
					cache = cipher.doFinal(data, offSet, inputLen - offSet);
				}
				out.write(cache, 0, cache.length);
				i++;
				offSet = i * MAX_ENCRYPT_BLOCK;
			}
 
			byte[] encryptedData = Base64.encodeBase64(out.toByteArray());
			out.close();
 
			return new String(encryptedData, "ASCII");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
 
	/**
	 * 私钥加密
	 * 
	 * @param content
	 *            待加密内容
	 * @param privateKey
	 *            私钥
	 * @param charset
	 *            content的字符集，如UTF-8, GBK, GB2312
	 * @return 密文内容 base64 ASCII
	 */
	public static String encryptByPrivateKey(String content, PrivateKey privateKey, String charset) {
		try {
			Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
			cipher.init(Cipher.ENCRYPT_MODE, privateKey);
			byte[] data = (charset == null || charset.isEmpty()) ? content.getBytes() : content.getBytes(charset);
			int inputLen = data.length;
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int offSet = 0;
			byte[] cache;
			int i = 0;
			// 对数据分段加密
			while (inputLen - offSet > 0) {
				if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
					cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
				} else {
					cache = cipher.doFinal(data, offSet, inputLen - offSet);
				}
				out.write(cache, 0, cache.length);
				i++;
				offSet = i * MAX_ENCRYPT_BLOCK;
			}
 
			byte[] encryptedData = Base64.encodeBase64(out.toByteArray());
			out.close();
 
			return new String(encryptedData, "ASCII");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
 
	/**
	 * 私钥解密
	 * 
	 * @param content
	 *            待解密内容(base64, ASCII)
	 * @param privateKey
	 *            私钥
	 * @param charset
	 *            加密前字符的字符集，如UTF-8, GBK, GB2312
	 * @return 明文内容
	 * @return
	 */
	public static String decryptByPrivateKey(String content, PrivateKey privateKey, String charset) {
		try {
			Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			byte[] encryptedData = Base64.decodeBase64(content);
			int inputLen = encryptedData.length;
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int offSet = 0;
			byte[] cache;
			int i = 0;
			// 对数据分段解密
			while (inputLen - offSet > 0) {
				if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
					cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
				} else {
					cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
				}
 
				out.write(cache, 0, cache.length);
				i++;
				offSet = i * MAX_DECRYPT_BLOCK;
			}
			byte[] decryptedData = out.toByteArray();
			out.close();
 
			return (charset == null || charset.isEmpty()) ? new String(decryptedData)
					: new String(decryptedData, charset);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
 
	/**
	 * 公钥解密
	 * 
	 * @param content
	 *            待解密内容(base64, ASCII)
	 * @param publicKey
	 *            公钥
	 * @param charset
	 *            加密前字符的字符集，如UTF-8, GBK, GB2312
	 * @return 明文内容
	 * @return
	 */
	public static String decryptByPublicKey(String content, PublicKey publicKey, String charset) {
		try {
			Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, publicKey);
			byte[] encryptedData = Base64.decodeBase64(content);
			int inputLen = encryptedData.length;
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int offSet = 0;
			byte[] cache;
			int i = 0;
			// 对数据分段解密
			while (inputLen - offSet > 0) {
				if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
					cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
				} else {
					cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
				}
 
				out.write(cache, 0, cache.length);
				i++;
				offSet = i * MAX_DECRYPT_BLOCK;
			}
			byte[] decryptedData = out.toByteArray();
			out.close();
 
			return (charset == null || charset.isEmpty()) ? new String(decryptedData)
					: new String(decryptedData, charset);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
 
	/**
	 * 
	 * @param signType 如：SHA1withRSA
	 * @param data
	 * @param publicKey
	 * @param sign base64字符串
	 * @return
	 * @throws Exception
	 */
	public static boolean verifySign(String signType, byte[] data, PublicKey publicKey, String sign) throws Exception {
		Signature signature = Signature.getInstance(signType);
		signature.initVerify(publicKey);
		signature.update(data);
		return signature.verify(Base64.decodeBase64(sign));
	}
	
	/**
	 * 
	 * @param signType 如：SHA1withRSA
	 * @param data
	 * @param privateKey
	 * @return base64字符串
	 * @throws Exception
	 */
	public static String sign(String signType, byte[] data, PrivateKey privateKey) throws Exception {
        Signature signature = Signature.getInstance(signType);
        signature.initSign(privateKey);
        signature.update(data);
        
        return Base64.encodeBase64String(signature.sign());
    }
	
	/**
	 * 从文件中获取私钥
	 * 
	 * @param filePath
	 * @return
	 */
	public static PrivateKey getPrivateKeyFromFile(String filePath){
        String privateKey = KeyStoreUtil.getKeyFromFile(RSA_PRIVATE_CACHE_KEY, filePath);
        PrivateKey privateKeyTwo = RSAUtil.readPrivateKey(privateKey);
        return privateKeyTwo;
    }
	
    
	/**
	 * 从文件中获取公钥
	 * 
	 * @param filePath
	 * @return
	 */
    public static PublicKey getPublicKeyFromFile(String filePath){
        String publicKey = KeyStoreUtil.getKeyFromFile(RSA_PUBLIC_CACHE_KEY, filePath);
        PublicKey publicKeyTwo = RSAUtil.readPublicKey(publicKey);
        return publicKeyTwo;
    }
    
    /**
     * 从字符串中获取私钥
     * 
     * @param keyStr	开头和结束不能包含“-----BEGIN PRIVATE KEY-----” 和 “-----END PRIVATE KEY-----” 需要删掉这2行
     * @return
     */
    public static PrivateKey getPrivateKeyFromString(String keyStr){
    	String privateKey = KeyStoreUtil.getKeyFromString(RSA_PRIVATE_CACHE_KEY, keyStr);
    	PrivateKey privateKeyTwo = RSAUtil.readPrivateKey(privateKey);
    	return privateKeyTwo;
    }
    
    
    /**
     * 从字符串中获取公钥
     * 
     * @param keyStr	开头和结束不能包含“-----BEGIN PUBLIC KEY-----” 和 “-----END PUBLIC KEY-----” 需要删掉这2行
     * @return
     */
    public static PublicKey getPublicKeyFromString(String keyStr){
    	String publicKey = KeyStoreUtil.getKeyFromString(RSA_PUBLIC_CACHE_KEY, keyStr);
    	PublicKey publicKeyTwo = RSAUtil.readPublicKey(publicKey);
    	return publicKeyTwo;
    }
}
